import React, { useState, useEffect, useCallback } from "react";
import {
  NavBar,
  Tabs,
  List,
  Card,
  Button,
  Toast,
  Dialog,
  Input,
  SpinLoading,
} from "antd-mobile";
import { useNavigate, useSearchParams } from "react-router-dom";
import styles from "../style/orders.module.css";
// 引入所有封装好的API
import {
  getOrderList,
  deleteOrder,
  confirmReceipt,
  cancelOrder as applyRefund,
  payPendingOrder
} from "../api/order";

// 类型定义
interface OrderItem {
  id: number;
  goods_id: number;
  address: string;
  address_desc: string;
  code: string;
  createtime: string;
  img: string;
  name: string;
  norm: string;
  num: number;
  price: string;
  status: string;
  status_title: string;
  tel: string;
  title: string;
}

interface ApiResponse<T> {
  code: number;
  message?: string;
  data: {
    list: T;
  };
}

interface StatusTab {
  title: string;
  key: string;
}

interface OrderActionParams {
  orderId: number;
  reason?: string;
}

const statusTabs: StatusTab[] = [
  { title: "全部", key: "0" },
  { title: "待付款", key: "1" },
  { title: "待发货", key: "2" },
  { title: "待收货", key: "3" },
  { title: "待评价", key: "4" },
];

const OrderPage: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState<string>("0");
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [refundReason, setRefundReason] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  // 初始化处理URL参数
  useEffect(() => {
    const statusParam = searchParams.get("status");
    const validStatus = statusTabs.some((tab) => tab.key === statusParam);
    setActiveTab(validStatus ? statusParam! : "0");
  }, [searchParams]);

  // 用户状态管理
  const [user] = useState(() => {
    try {
      const userData = localStorage.getItem("user");
      return userData ? JSON.parse(userData) : null;
    } catch (e) {
      console.error("解析用户数据失败:", e);
      return null;
    }
  });

  // 获取订单数据 - 使用封装的API
  const fetchOrders = useCallback(
    async (status?: number) => {
      if (!user?.data?.id) {
        setError("用户未登录");
        setLoading(false);
        return;
      }
      setLoading(true);
      setError(null);
      try {
        // 使用封装的API获取订单列表
        const res = await getOrderList({
          user_id: user.data.id,
          ...(status !== undefined && { status }),
        });

        if (res.data.code === 1) {
          setOrders(res.data.data.list);
          console.log(res.data.data.list);
        } else {
          setError(res.data.message || "获取订单数据失败");
          setOrders([]);
        }
      } catch (err) {
        console.error("请求订单数据出错:", err);
        setOrders([]);
      } finally {
        setLoading(false);
      }
    },
    [user]
  );

  // 处理订单操作 - 使用封装的API
  const handleOrderAction = useCallback(
    async (action: string, { orderId, reason }: OrderActionParams) => {
      if (!user?.data?.token) {
        Toast.show("请先登录");
        return;
      }

      try {
        let result;
        switch (action) {
          case "delete":
            result = await deleteOrder({ order_id: orderId });
            break;
          case "confirm":
            result = await confirmReceipt({ order_id: orderId });
            break;
          case "refund":
            result = await applyRefund({ order_id: orderId, reason });
            break;
          default:
            throw new Error("未知的操作类型");
        }

        if (result.data.code === 1) {
          Toast.show({
            icon: "success",
            content:
              action === "delete"
                ? "删除成功"
                : action === "confirm"
                ? "确认收货成功"
                : "退款申请已提交",
          });
          
          // 刷新订单列表
          fetchOrders(activeTab === "0" ? undefined : Number(activeTab));
        } else {
          throw new Error(result.data.message || "操作失败");
        }
      } catch (err) {
        console.error("订单操作失败:", err);
        Toast.show({
          icon: "fail",
        });
      }
    },
    [activeTab, fetchOrders, user]
  );

  // 删除订单
  const handleDelete = useCallback(
    (orderId: number) => {
      Dialog.confirm({
        title: "确认删除",
        content: "确定要删除该订单吗？此操作不可恢复。",
        confirmText: "确认删除",
        cancelText: "取消",
        onConfirm: () => handleOrderAction("delete", { orderId }),
      });
    },
    [handleOrderAction]
  );

  // 确认收货
  const handleConfirm = useCallback(
    (orderId: number) => {
      Dialog.confirm({
        title: "确认收货",
        content: "请确认您已收到商品且商品完好无损",
        confirmText: "确认收货",
        cancelText: "取消",
        onConfirm: () => handleOrderAction("confirm", { orderId }),
      });
    },
    [handleOrderAction]
  );

  // 处理退款
  const handleRefund = useCallback(
    (orderId: number) => {
      Dialog.confirm({
        title: "申请退款",
        content: (
          <div style={{ padding: "12px 0" }}>
            <Input
              placeholder="请输入退款原因（必填）"
              value={refundReason}
              onChange={setRefundReason}
              clearable
            />
          </div>
        ),
        confirmText: "提交申请",
        cancelText: "取消",
        onConfirm: () => {
          if (!refundReason.trim()) {
            Toast.show("请填写退款原因");
            return;
          }
          handleOrderAction("refund", { orderId, reason: refundReason });
          setRefundReason("");
        },
      });
    },
    [handleOrderAction, refundReason]
  );

  // 渲染操作按钮
  const renderActions = useCallback(
    (order: OrderItem) => {
      const commonProps = {
        size: "small" as const,
        style: {
          marginLeft: 8,
          border: "1px solid #ccc", // 添加边框
          borderRadius: "20px", // 添加圆角
          fontSize: "12px",
          height: "30px",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
        },
      };

      switch (order.status) {
        case "1":
          return [
            <Button
              key="pay"
              color="primary"
              {...commonProps}
              onClick={() => payPendingOrder({order_id: order.id})} // 直接调用支付API
            >
              立即付款
            </Button>,
            <Button
              key="refund"
              color="danger"
              fill="outline"
              {...commonProps}
              onClick={() => handleRefund(order.id)}
            >
              取消订单
            </Button>,
          ];
        case "2":
          return [
            <Button
              key="refund"
              fill="outline"
              {...commonProps}
              onClick={() => handleRefund(order.id)}
            >
              退款
            </Button>,
            <Button
              key="service"
              color="default"
              fill="none"
              {...commonProps}
              onClick={() => {
                Dialog.alert({
                  title: "",
                  content: "已申请售后，请耐心等待",
                });
              }}
            >
              申请售后
            </Button>,
            <Button
              key="remind"
              color="danger"
              fill="none"
              {...commonProps}
              onClick={() => {
                Dialog.alert({
                  title: "",
                  content: "您的商品已催，请耐心等待",
                });
              }}
            >
              催发货
            </Button>,
          ];
        case "3":
          return [
            <Button
              key="refund"
              color="danger"
              fill="outline"
              {...commonProps}
              onClick={() => handleRefund(order.id)}
            >
              退款
            </Button>,
            <Button key="service" color="default" fill="none" {...commonProps}>
              申请售后
            </Button>,
            <Button key="track" color="default" fill="none" {...commonProps}>
              查看物流
            </Button>,
            <Button
              key="confirm"
              color="primary"
              {...commonProps}
              onClick={() => handleConfirm(order.id)}
            >
              确认收货
            </Button>,
          ];
        case "4":
          return [
            <Button
              key="comment"
              color="primary"
              {...commonProps}
              onClick={() => navigate(`/comment/${order.id}`)}
            >
              去评价
            </Button>,
          ];
        case "5":
          return [
            <Button
              key="delete"
              color="default"
              fill="none"
              {...commonProps}
              onClick={() => handleDelete(order.id)}
            >
              删除订单
            </Button>,
            <Button
              key="rebuy"
              color="primary"
              fill="none"
              {...commonProps}
              onClick={() => navigate(`/product/${order.goods_id}`)}
            >
              再次购买
            </Button>,
          ];
        case "6":
          return [
            <Button key="contact" color="default" fill="none" {...commonProps}>
              联系客服
            </Button>,
          ];
        case "7":
          return [
            <Button
              key="delete"
              color="default"
              fill="none"
              {...commonProps}
              onClick={() => handleDelete(order.id)}
            >
              删除订单
            </Button>,
            <Button
              key="rebuy"
              color="primary"
              fill="none"
              {...commonProps}
              onClick={() => navigate(`/product/${order.goods_id}`)}
            >
              再次购买
            </Button>,
          ];
        case "8":
          return [
            <Button
              key="delete"
              color="default"
              fill="none"
              {...commonProps}
              onClick={() => handleDelete(order.id)}
            >
              删除订单
            </Button>,
            <Button
              key="rebuy"
              color="primary"
              fill="none"
              {...commonProps}
              onClick={() => navigate(`/product/${order.goods_id}`)}
            >
              再次购买
            </Button>,
          ];
        default:
          return [];
      }
    },
    [navigate, handleConfirm, handleDelete, handleRefund]
  );

  // 渲染订单卡片
  const renderOrderCard = useCallback(
    (order: OrderItem) => (
      <Card
        key={order.id}
        className={`${styles.orderCard} ${styles.cardBorder}`}
      >
        <div className={styles.cardHeader} onClick={() => orderdetails(order)}>
          <span className={styles.orderNo}>订单号：{order.code}</span>
          <span className={styles[`status-${order.status}`]}>
            {order.status_title}
          </span>
        </div>

        <div className={styles.goodsItem} onClick={() => orderdetails(order)}>
          <img
            src={order.img}
            alt={order.title}
            onError={(e) => {
              (e.target as HTMLImageElement).src = "/img/product-default.png";
            }}
          />
          <div className={styles.goodsInfo}>
            <div className={styles.goodsTitle}>
              <span onClick={() => navigate(`/product/${order.goods_id}`)}>
                {order.title}
              </span>
              <p>¥{(Number(order.price) * Number(order.num)).toFixed(2)}</p>
            </div>
            <div className={styles.goodsSpec}>
              <span>{order.norm || order.title}</span>
              <span>x{order.num}</span>
            </div>
            <div className={styles.orderTime}>
              下单时间：{new Date(order.createtime).toLocaleString()}
            </div>
          </div>
        </div>

        <div className={styles.actionButtons}>{renderActions(order)}</div>
      </Card>
    ),
    [navigate, renderActions]
  );
  
  // ==================点击跳转到订单详情==================
  function orderdetails(order: OrderItem) {
    // 存储订单详情数据到sessionStorage
    sessionStorage.setItem(
      "orderDetails",
      JSON.stringify({
        orderNo: order.code,
        productName: order.title,
        price: (Number(order.price) * Number(order.num)).toFixed(2),
        quantity: order.num,
        orderTime: new Date(order.createtime).toLocaleString(),
        specifications: order.norm || order.title, // 使用规格或标题作为规格描述
        status: order.status_title,
        productImage: order.img,
        address: order.address,
        addressDesc: order.address_desc,
        phone: order.tel,
      })
    );

    navigate("/orderdetails");
  }

  // 渲染内容区域
  const renderContent = () => {
    if (loading) {
      return (
        <div className={styles.loadingContainer}>
          <SpinLoading style={{ "--size": "48px" }} />
          <p>加载订单中...</p>
        </div>
      );
    }

    if (error) {
      return (
        <div className={styles.errorContainer}>
          <img src="/img/error.png" alt="错误" />
          <p>{error}</p>
          <Button
            color="primary"
            size="small"
            onClick={() =>
              fetchOrders(activeTab === "0" ? undefined : Number(activeTab))
            }
          >
            重新加载
          </Button>
        </div>
      );
    }

    if (orders.length === 0) {
      return (
        <div className={styles.emptyContainer}>
          <p>暂无相关订单</p>
          <Button
            color="primary"
            onClick={() => navigate("/home")}
            style={{ marginTop: 16 }}
          >
            去逛逛
          </Button>
        </div>
      );
    }

    return <List>{orders.map(renderOrderCard)}</List>;
  };

  // 处理Tab切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setSearchParams({ status: key });
  };

  // 数据加载
  useEffect(() => {
    const status = activeTab === "0" ? undefined : Number(activeTab);
    console.log("加载订单状态:", status);

    fetchOrders(status);
  }, [activeTab, fetchOrders]);

  return (
    <div className={styles.container}>
      <NavBar
        onBack={() => navigate("/me")}
        right={
          <span
            onClick={() => navigate("/customer-service")}
            style={{ fontSize: 14, color: "#666" }}
          ></span>
        }
      >
        我的订单
      </NavBar>

      <Tabs
        activeKey={activeTab}
        onChange={handleTabChange}
        style={{
          "--title-font-size": "14px",
          "--active-title-color": "#FF8000",
          "--active-line-color": "#FF8000",
        }}
      >
        {statusTabs.map((tab) => (
          <Tabs.Tab title={tab.title} key={tab.key} />
        ))}
      </Tabs>

      <div className={styles.contentWrapper}>{renderContent()}</div>
    </div>
  );
};

export default React.memo(OrderPage);